package com.starsea.book.ui.newpage

import android.os.Bundle
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import com.starsea.book.R
import com.starsea.book.base.VMBaseActivity
import com.starsea.book.constant.EventBus
import com.starsea.book.databinding.ActivityBookShelfChildBinding
import com.starsea.book.ui.config.ConfigTag
import com.starsea.book.ui.config.ConfigViewModel
import com.starsea.book.ui.config.ThemeConfigFragment
import com.starsea.book.ui.main.bookshelf.style1.books.BooksFragment
import com.starsea.book.ui.newpage.entity.BookShelfEntity
import com.starsea.book.utils.observeEvent
import com.starsea.book.utils.viewbindingdelegate.viewBinding

class BookGroupShelfChildActivity : VMBaseActivity<ActivityBookShelfChildBinding, ConfigViewModel>() {

    override val binding by viewBinding(ActivityBookShelfChildBinding::inflate)
    override val viewModel by viewModels<ConfigViewModel>()

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        replaceFragment<BooksFragment>("books_fragment")
    }

    inline fun <reified T : Fragment> replaceFragment(configTag: String) {
        intent.putExtra("configTag", configTag)
        @Suppress("DEPRECATION")
//        val configFragment = supportFragmentManager.findFragmentByTag(configTag)
//            ?: T::class.java.newInstance()

        val entity: BookShelfEntity = intent.getSerializableExtra("entity") as BookShelfEntity
        val configFragment = BooksFragment(1, entity)
        supportFragmentManager.beginTransaction()
            .replace(R.id.configFrameLayout, configFragment, configTag)
            .commit()
    }

    override fun observeLiveBus() {
        super.observeLiveBus()
        observeEvent<String>(EventBus.RECREATE) {
            recreate()
        }
    }

    override fun finish() {
        if (supportFragmentManager.findFragmentByTag(ConfigTag.COVER_CONFIG) != null
            || supportFragmentManager.findFragmentByTag(ConfigTag.WELCOME_CONFIG) != null
        ) {
            replaceFragment<ThemeConfigFragment>(ConfigTag.THEME_CONFIG)
        } else {
            super.finish()
        }
    }

}